package cn.smbms.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import tk.mybatis.mapper.entity.Example;
import cn.smbms.dao.PermissionMapper;
import cn.smbms.dao.RoleMapper;
import cn.smbms.dao.RolePermissionMapper;
import cn.smbms.pojo.Permission;
import cn.smbms.pojo.Role;
import cn.smbms.pojo.RolePermission;
import cn.smbms.service.RoleService;
import cn.smbms.utils.Constants;

@Service("roleService")
public class RoleServiceImpl implements RoleService {
	
	@Resource(name="roleMapper")
	private RoleMapper roleMapper;
	
	@Resource(name="permissionMapper")
	private PermissionMapper permissionMapper;

	@Resource(name="rolePermissionMapper")
	private RolePermissionMapper rolePermissionMapper;

	public List<Role> getRoleList() {
		//
		return roleMapper.selectAll();
	}


	public List<Role> getRoleListByRoleName(String roleName) {
		//
		Example ex = new Example(Role.class);
		if(roleName!=null && !"".equals(roleName))
			ex.createCriteria().andLike("roleName", "%"+roleName+"%");
		//RowBounds rbs = new RowBounds((page - 1) * rows, rows);
		//return roleMapper.select(role);
		return roleMapper.selectByExample(ex);
	}


	public List<Permission> getPermissionList() {
		//
		return permissionMapper.selectAll();
	}


	public Role getRoleById(Integer roleid) {
		//
		return roleMapper.selectByPrimaryKey(roleid);
	}


	public int updateRole(Role role) {
		//
		return roleMapper.updateByPrimaryKeySelective(role);
	}

	@CacheEvict(value=Constants.PERMISSION_CACHE, key="#id")
	public int updateRolePermission(Integer id, Integer[] permission) {
		//清除原有角色权限
		Example ex = new Example(RolePermission.class);
		ex.createCriteria().andEqualTo("roleId", id);
		rolePermissionMapper.deleteByExample(ex);
		//新增加角色权限
		int i = 0;
		RolePermission role = new RolePermission();
		role.setRoleId(id);
		for(Integer p : permission) {
			role.setPermId(p);
			i = rolePermissionMapper.insertSelective(role);
		}
		return i;
	}


	public List<RolePermission> getRolePermissionByRoleId(Integer roleid) {
		//
		Example ex = new Example(RolePermission.class);
		ex.createCriteria().andEqualTo("roleId", roleid);
		return rolePermissionMapper.selectByExample(ex);
	}

	@Cacheable(value=Constants.PERMISSION_CACHE, key="#userRole")
	public List<Permission> getPermissionByRoleId(Integer userRole) {
		//
		return roleMapper.getPermissionByRoleId(userRole);
	}


}
